// components/ProgressSliderModal.js

export default class ProgressSliderModal {
  constructor(options = {}, textRenderer, screenAdapter, resourceManager) {
    // 弹窗尺寸和位置
    this.width = options.width || 1002;
    this.height = options.height || 560;
    this.x = (options.canvasWidth || this.width) / 2 - this.width / 2;
    this.y = (options.canvasHeight || this.height) / 2 - this.height / 2;
    this.type = options.type || 'BUY';
    this.color = options.color || '#D31B4B';

    // 样式配置
    this.bgColor = '#282E50';
    this.overlayColor = 'rgba(0, 0, 0, 0.5)';
    this.titleColor = '#333333';

    // 选项框配置
    this.boxes = [
      { text: '25%', value: 0.25, selected: false },
      { text: '50%', value: 0.5, selected: false },
      { text: '75%', value: 0.75, selected: false },
      { text: '100%', value: 1.0, selected: false },
    ];
    this.boxConfig = {
      firstBoxLeftX: 610,
      startY: 402,
      width: 118,
      height: 50,
      borderRadius: 8,
      margin: 24,
      defaultBorderColor: '#8799C8',
      selectedBgColor: '#F1A039',
      textColor: '#FFFFFF',
      unselectedTextColor: '#8799C8',
      // 新增：选项框悬停效果
      hoverBgColor: 'rgba(241, 160, 57, 0.1)',
    };

    // 滑块配置
    this.sliderConfig = {
      x: 608,
      y: 334,
      width: 546,
      height: 16,
      knobWidth: 26,
      knobHeight: 32,
      knobRadius: 4,
      trackBgColor: '#ACADB8',
      progressColor: '#D31B4B',
      knobColor: '#FFFFFF',
      // 【新增】扩大触摸区域的配置
      touchPadding: 20, // 触摸区域扩展20px
      // 【新增】滑块阴影效果
      knobShadowColor: 'rgba(0, 0, 0, 0.3)',
      knobShadowBlur: 4,
      knobShadowOffsetY: 2,
    };

    // 确定按钮配置
    this.buttonConfig = {
      width: 224,
      height: 72,
      y: 540,
      bgColor: '#F1A039',
      textColor: '#FFFFFF',
      borderRadius: 8,
      // 【新增】按钮悬停效果
      hoverBgColor: '#E8942F',
      pressedBgColor: '#D18828',
    };

    // 交互状态
    this.isVisible = false;
    this.baseValue = 100;
    this.currentSliderValue = 0;
    this.isDragging = false;
    
    // 【新增】悬停状态
    this.hoveredBoxIndex = -1;
    this.isButtonHovered = false;
    this.isButtonPressed = false;

    this.screenAdapter = screenAdapter;
    this.textRenderer = textRenderer;
    this.resourceManager = resourceManager;

    // 事件回调
    this.onBtnClick = options.onBtnClick || null;
    this.onClose = options.onClose || null;
  }

  /**
   * 显示弹窗
   * @param {number} baseValue - 页面传入的基础值
   * @param {number} initialValue - 初始的计算值
   */
  show(baseValue, initialValue) {
    this.isVisible = true;
    this.baseValue = baseValue;
    this.currentSliderValue = initialValue;
    this.hoveredBoxIndex = -1;
    this.isButtonHovered = false;
    this.isButtonPressed = false;

    // 根据初始值设置滑块位置和选项框状态
    this._updateBoxSelectionFromValue(this.currentSliderValue);
  }

  hide() {
    this.isVisible = false;
    this.isDragging = false;
    this.hoveredBoxIndex = -1;
    this.isButtonHovered = false;
    this.isButtonPressed = false;
    this.onClose && this.onClose();
  }

  // --- 事件处理 ---

  handleTouchStart(touchX, touchY) {
    if (!this.isVisible) return false;

    // 【优化】检查滑块触摸区域（扩大后的区域）
    const touchArea = this._getKnobTouchArea();
    if (touchX >= touchArea.x && touchX <= touchArea.x + touchArea.width &&
      touchY >= touchArea.y && touchY <= touchArea.y + touchArea.height) {
      this.isDragging = true;
      return true;
    }

    // 检查是否点击了弹窗关闭按钮
    if (this._isCloseButtonClicked(touchX, touchY)) {
      this.hide();
      return true;
    }

    // 检查选项框点击
    const clickedBoxIndex = this._getClickedBoxIndex(touchX, touchY);
    if (clickedBoxIndex !== -1) {
      const box = this.boxes[clickedBoxIndex];
      this.currentSliderValue = this.baseValue * box.value;
      this._updateBoxSelectionFromValue(this.currentSliderValue);
      return true;
    }

    // 检查确定按钮
    if (this._isButtonClicked(touchX, touchY)) {
      this.isButtonPressed = true;
      this.onBtnClick && this.onBtnClick(Math.round(this.currentSliderValue));
      // 延迟隐藏，让用户看到按压效果
      setTimeout(() => this.hide(), 100);
      return true;
    }

    return false;
  }

  handleTouchMove(touchX, touchY) {
    if (!this.isVisible) return false;

    // 更新悬停状态
    this._updateHoverStates(touchX, touchY);

    if (!this.isDragging) return false;

    // 健壮性检查
    if (typeof this.baseValue !== 'number' || this.baseValue <= 0) {
      console.error("错误: baseValue 无效，无法移动滑块。", this.baseValue);
      this.isDragging = false;
      return false;
    }

    const { x, width } = this.sliderConfig;
    const relativeX = touchX - x;
    const clampedX = Math.max(0, Math.min(width, relativeX));
    const percentage = clampedX / width;

    this.currentSliderValue = this.baseValue * percentage;
    this._updateBoxSelectionFromValue(this.currentSliderValue);

    return true;
  }

  handleTouchEnd() {
    if (this.isDragging) {
      this.isDragging = false;
      return true;
    }
    
    if (this.isButtonPressed) {
      this.isButtonPressed = false;
      return true;
    }
    
    return false;
  }

  // --- 绘制 ---
  draw(ctx) {
    if (!this.isVisible) return;

    // 1. 遮罩
    ctx.fillStyle = this.overlayColor;
    ctx.fillRect(0, 0, this.screenAdapter.DESIGN_WIDTH, this.screenAdapter.DESIGN_HEIGHT);

    // 2. 背景
    this._drawBackground(ctx);

    // 3. 标题和信息文本
    this._drawTitleAndInfo(ctx);

    // 4. 滑块
    this._drawSlider(ctx);

    // 5. 选项框
    this._drawOptionBoxes(ctx);

    // 6. 确定按钮
    this._drawConfirmButton(ctx);
  }

  // --- 私有辅助方法 ---

  /**
   * 获取滑块的视觉矩形区域
   */
  _getKnobRect() {
    const { x, y, width, knobWidth, knobHeight } = this.sliderConfig;
    const progressPercentage = Math.max(0, Math.min(1, this.currentSliderValue / this.baseValue));
    const knobCenterXOnTrack = width * progressPercentage;
    const clampedKnobCenterX = Math.max(0, Math.min(width, knobCenterXOnTrack));
    const knobX = x + clampedKnobCenterX - knobWidth / 2;
    const knobY = y + (this.sliderConfig.height - knobHeight) / 2;
    return { x: knobX, y: knobY, width: knobWidth, height: knobHeight };
  }

  /**
   * 【新增】获取滑块的触摸区域（扩大后的区域）
   */
  _getKnobTouchArea() {
    const knob = this._getKnobRect();
    const padding = this.sliderConfig.touchPadding;
    return {
      x: knob.x - padding,
      y: knob.y - padding,
      width: knob.width + padding * 2,
      height: knob.height + padding * 2
    };
  }

  /**
   * 检查关闭按钮是否被点击
   */
  _isCloseButtonClicked(touchX, touchY) {
    return touchX >= 1246 && touchX <= 1286 && touchY >= 110 && touchY <= 150;
  }

  /**
   * 获取被点击的选项框索引
   */
  _getClickedBoxIndex(touchX, touchY) {
    const { firstBoxLeftX, width, height, margin } = this.boxConfig;
    for (let i = 0; i < this.boxes.length; i++) {
      const boxX = firstBoxLeftX + i * (width + margin);
      if (touchX >= boxX && touchX <= boxX + width &&
        touchY >= this.boxConfig.startY && touchY <= this.boxConfig.startY + height) {
        return i;
      }
    }
    return -1;
  }

  /**
   * 检查确定按钮是否被点击
   */
  _isButtonClicked(touchX, touchY) {
    const buttonY = this.buttonConfig.y;
    const buttonX = this.x + (this.width - this.buttonConfig.width) / 2;
    return touchX >= buttonX && touchX <= buttonX + this.buttonConfig.width &&
      touchY >= buttonY && touchY <= buttonY + this.buttonConfig.height;
  }

  /**
   * 更新悬停状态
   */
  _updateHoverStates(touchX, touchY) {
    // 更新选项框悬停状态
    this.hoveredBoxIndex = this._getClickedBoxIndex(touchX, touchY);
    
    // 更新按钮悬停状态
    this.isButtonHovered = this._isButtonClicked(touchX, touchY);
  }

  /**
   * 绘制背景
   */
  _drawBackground(ctx) {
    const backgroundImg = this.resourceManager.getImage('gamePop');
    if (backgroundImg) {
      ctx.drawImage(backgroundImg, this.x, this.y, this.width, this.height);
    }
  }

  /**
   * 绘制标题和信息文本
   */
  _drawTitleAndInfo(ctx) {
    // 标题
    this.textRenderer.drawText(
      `${this.type === 'BUY' ? '买入' : '卖出'}`,
      this.screenAdapter.DESIGN_WIDTH / 2,
      116,
      `32px ${this.textRenderer.systemFont}`,
      this.color,
      'center',
      'top'
    );

    // 最大可买/可卖信息
    const actionText = this.type === 'BUY' ? '最大可买：' : '最大可卖：';
    this.textRenderer.drawText(actionText, 438, 234, `32px ${this.textRenderer.systemFont}`, '#FFFFFF', 'left', 'top');
    this.textRenderer.drawText(`${this.baseValue} 手`, 608, 234, `32px ${this.textRenderer.systemFont}`, '#FFFFFF', 'left', 'top');
    
    const selectText = this.type === 'BUY' ? '选择买入:' : '选择卖出：';
    this.textRenderer.drawText(selectText, 438, 320, `32px ${this.textRenderer.systemFont}`, '#FFFFFF', 'left', 'top');
    
    // 当前值显示
    const displayValue = Math.round(this.currentSliderValue);
    this.textRenderer.drawText(`${displayValue.toString()} 手`, 1190, 326, `24px ${this.textRenderer.systemFont}`, '#ffffff', 'left', 'top');
  }

  /**
   * 绘制滑块
   */
  _drawSlider(ctx) {
    const { x, y, width, height, trackBgColor, knobColor, knobShadowColor, knobShadowBlur, knobShadowOffsetY } = this.sliderConfig;

    // 轨道背景
    ctx.fillStyle = trackBgColor;
    ctx.fillRect(x, y, width, height);

    // 进度条
    const progressPercentage = Math.max(0, Math.min(1, this.currentSliderValue / this.baseValue));
    const progressWidth = width * progressPercentage;
    ctx.fillStyle = this.color;
    ctx.fillRect(x, y, progressWidth, height);

    // 滑块（带阴影）
    const knob = this._getKnobRect();
    
    // 绘制阴影
    ctx.save();
    ctx.shadowColor = knobShadowColor;
    ctx.shadowBlur = knobShadowBlur;
    ctx.shadowOffsetY = knobShadowOffsetY;
    
    ctx.fillStyle = knobColor;
    this._drawRoundRect(ctx, knob.x, knob.y, knob.width, knob.height, this.sliderConfig.knobRadius);
    ctx.fill();
    ctx.restore();
  }

  /**
   * 绘制选项框
   */
  _drawOptionBoxes(ctx) {
    const { firstBoxLeftX, startY, width: boxW, height: boxH, borderRadius, margin, 
            defaultBorderColor, selectedBgColor, textColor, unselectedTextColor, hoverBgColor } = this.boxConfig;

    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    ctx.font = '20px sans-serif';

    for (let i = 0; i < this.boxes.length; i++) {
      const box = this.boxes[i];
      const boxX = firstBoxLeftX + i * (boxW + margin);

      // 绘制背景
      if (box.selected) {
        ctx.fillStyle = selectedBgColor;
        this._drawRoundRect(ctx, boxX, startY, boxW, boxH, borderRadius);
        ctx.fill();
        ctx.fillStyle = textColor;
      } else if (i === this.hoveredBoxIndex) {
        // 悬停效果
        ctx.fillStyle = hoverBgColor;
        this._drawRoundRect(ctx, boxX, startY, boxW, boxH, borderRadius);
        ctx.fill();
        
        ctx.strokeStyle = selectedBgColor;
        ctx.lineWidth = 2;
        this._drawRoundRect(ctx, boxX, startY, boxW, boxH, borderRadius);
        ctx.stroke();
        ctx.fillStyle = selectedBgColor;
      } else {
        ctx.strokeStyle = defaultBorderColor;
        ctx.lineWidth = 2;
        this._drawRoundRect(ctx, boxX, startY, boxW, boxH, borderRadius);
        ctx.stroke();
        ctx.fillStyle = unselectedTextColor;
      }
      
      // 绘制文本
      ctx.fillText(box.text, boxX + boxW / 2, startY + boxH / 2);
    }
  }

  /**
   * 绘制确定按钮
   */
  _drawConfirmButton(ctx) {
    const buttonX = this.x + (this.width - this.buttonConfig.width) / 2;
    const buttonY = this.buttonConfig.y;
    const { width, height, borderRadius, textColor, bgColor, hoverBgColor, pressedBgColor } = this.buttonConfig;

    // 确定按钮背景颜色
    let currentBgColor = bgColor;
    if (this.isButtonPressed) {
      currentBgColor = pressedBgColor;
    } else if (this.isButtonHovered) {
      currentBgColor = hoverBgColor;
    }

    // 获取按钮图片
    let btn = null;
    if (this.type === 'BUY') {
      btn = this.resourceManager.getImage('buyIcon');
    } else {
      btn = this.resourceManager.getImage('sellIcon');
    }

    if (btn) {
      ctx.drawImage(btn, buttonX - 7, buttonY - 2, 239, 88);
    }

    // 绘制按钮文字
    this.textRenderer.drawText(
      this.type === 'BUY' ? '买' : '卖',
      this.screenAdapter.DESIGN_WIDTH / 2,
      575,
      `32px ${this.textRenderer.systemFont}`,
      textColor,
      'center',
      'top'
    );
  }

  /**
   * 更新选项框选中状态
   */
  _updateBoxSelectionFromValue(value) {
    const percentage = value / this.baseValue;
    let foundMatch = false;
    
    this.boxes.forEach(box => {
      // 使用容差避免浮点数精度问题
      if (Math.abs(percentage - box.value) < 0.01) {
        box.selected = true;
        foundMatch = true;
      } else {
        box.selected = false;
      }
    });
    
    // 如果没有匹配项，确保所有都未选中
    if (!foundMatch) {
      this.boxes.forEach(box => box.selected = false);
    }
  }

  /**
   * 绘制圆角矩形
   */
  _drawRoundRect(ctx, x, y, width, height, radius) {
    ctx.beginPath();
    ctx.moveTo(x + radius, y);
    ctx.lineTo(x + width - radius, y);
    ctx.arc(x + width - radius, y + radius, radius, -Math.PI / 2, 0);
    ctx.lineTo(x + width, y + height - radius);
    ctx.arc(x + width - radius, y + height - radius, radius, 0, Math.PI / 2);
    ctx.lineTo(x + radius, y + height);
    ctx.arc(x + radius, y + height - radius, radius, Math.PI / 2, Math.PI);
    ctx.lineTo(x, y + radius);
    ctx.arc(x + radius, y + radius, radius, Math.PI, -Math.PI / 2);
    ctx.closePath();
  }
}
